/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.zookeeper.server;

import org.apache.jute.Record;
import org.apache.log4j.Logger;
import org.apache.zookeeper.KeeperException.Code;
import org.apache.zookeeper.ZooDefs.OpCode;
import org.apache.zookeeper.proto.PrepareDataRequest;
import org.apache.zookeeper.proto.SetDataRequest;
import org.apache.zookeeper.server.paxos2.*;
import org.apache.zookeeper.server.quorum.ProposalRequestProcessor;
import org.apache.zookeeper.txn.ErrorTxn;
import org.apache.zookeeper.txn.PrepareDataTxn;
import org.apache.zookeeper.txn.SetDataTxn;
import org.apache.zookeeper.txn.TxnHeader;

import java.nio.ByteBuffer;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * This request processor is generally at the start of a RequestProcessor
 * change. It sets up any transactions associated with requests that change the
 * state of the system. It counts on ZooKeeperServer to update
 * outstandingRequests, so that it can take into account transactions that are
 * in the queue to be applied when generating a transaction.
 */
public class PrepRequestProcessor extends Thread implements RequestProcessor {
    private static final Logger LOG = Logger
            .getLogger(PrepRequestProcessor.class);

    static boolean skipACL;

    static {
        skipACL = System.getProperty("zookeeper.skipACL", "no").equals("yes");
        if (skipACL) {
            LOG.info("zookeeper.skipACL==\"yes\", ACL checks will be skipped");
        }
    }

    /**
     * this is only for testing purposes. should never be useed otherwise
     */
    private static boolean failCreate = false;

    LinkedBlockingQueue<Request> submittedRequests = new LinkedBlockingQueue<Request>();

    RequestProcessor nextProcessor;

    ZooKeeperServer zks;

    public PrepRequestProcessor(ZooKeeperServer zks,
                                RequestProcessor nextProcessor) {
        super("ProcessThread:" + zks.getClientPort());
        this.nextProcessor = nextProcessor;
        this.zks = zks;
    }

    /**
     * method for tests to set failCreate
     *
     * @param b
     */
    public static void setFailCreate(boolean b) {
        failCreate = b;
    }

    @Override
    public void run() {
        try {
            while (true) {
                Request request = submittedRequests.poll(Configuration.batchWaitTime, TimeUnit.MILLISECONDS);
                long traceMask = ZooTrace.CLIENT_REQUEST_TRACE_MASK;
                if (request!= null && request.type == OpCode.ping) {
                    System.out.println("received ping");
                    traceMask = ZooTrace.CLIENT_PING_TRACE_MASK;
                }
                if (LOG.isTraceEnabled()) {
                    ZooTrace.logRequest(LOG, traceMask, 'P', request, "");
                }
                if (Request.requestOfDeath == request) {
                    break;
                }
                //System.out.println("prepare queue "+submittedRequests.size());
                pRequest(request);
            }
        } catch (InterruptedException e) {
            LOG.error("Unexpected interruption", e);
        }
        LOG.info("PrepRequestProcessor exited loop!");
    }

    /**
     * This method will be called inside the ProcessRequestThread, which is a
     * singleton, so there will be a single thread calling this code.
     *
     * @param request
     */
    @SuppressWarnings("unchecked")
    protected void pRequest(Request request) {
	if(submittedRequests.size()>500)
	    System.out.println("pre size="+submittedRequests.size());
        if(request == null){
            if(nextProcessor instanceof ProposalRequestProcessor){
                nextProcessor.processRequest(request);
            }
            return;
        }
        // LOG.info("Prep>>> cxid = " + request.cxid + " type = " +
        // request.type + " id = 0x" + Long.toHexString(request.sessionId));
        //System.out.print("prepare request "+request);
        if (request.type != OpCode.boloskyGetData && request.cxid > -2 && request.cxid < ReplyCache.getFirstCxid(request.sessionId)) {
            System.out.println("Old request " + request.sessionId + " " + request.cxid + " first " + ReplyCache.getFirstCxid(request.sessionId));
            if(request.type == OpCode.prepareData)
		Configuration.decreaseOutstanding();
	    return;
        }
        ByteBuffer reply = ReplyCache.getReply(request.sessionId, request.cxid);
        if (reply != null) {
            System.out.println("Retransmit " + request.sessionId + " " + request.cxid);
            ServerCnxn cnxn = zks.getServerCnxnFactory().getServerCnxn(request.sessionId);
            ((NIOServerCnxn) cnxn).sendBuffer(reply);
	    if(request.type == OpCode.prepareData)
	        Configuration.decreaseOutstanding();
            return;
        }
        if (request.type == OpCode.setData && ReplyCache.getLastOrdered(request.sessionId) != -1
                && request.cxid != ReplyCache.getLastOrdered(request.sessionId) + 1) {
            System.out.println("Order aborted " + request.cxid + " expected " + (ReplyCache.getLastOrdered(request.sessionId) + 1)
                    + " lastExecuted=" + ReplyCache.getLastCxid(request.sessionId));
            return;
        }


        TxnHeader txnHeader = null;
        Record txn = null;
        try {
            switch (request.type) {

                case OpCode.setData:
                    txnHeader = new TxnHeader(request.sessionId, request.cxid, request.nonce,
                            zks.getNextZxid(), zks.getTime(), OpCode.setData);
                    SetDataRequest setDataRequest = new SetDataRequest();
                    request.request.rewind();
                    ZooKeeperServer.byteBuffer2Record(request.request,
                            setDataRequest);
                    long blockId = setDataRequest.getBlockId();

                    txn = new SetDataTxn(request.sessionId, blockId, setDataRequest.getData());
                    break;
                case OpCode.prepareData:
		    PrepareDataRequest prepareDataRequest = new PrepareDataRequest();
                    request.request.rewind();
                    prepareDataRequest.setClientId(request.request.getLong());
                    prepareDataRequest.setCount(request.request.getInt());
                    int size = request.request.getInt();
                    if(size!= Configuration.blockSize)
                        throw new RuntimeException("mismatch");
                    byte[] data = MemoryBuffer.allocateBuffer();//new byte[Configuration.blockSize];
                    request.request.get(data);
                    prepareDataRequest.setData(data);
                    //LOG.info("Put " + request.sessionId+" "+request.cxid + " into data cache");
                    PrepareDataCache.put(prepareDataRequest.getClientId(), request.cxid, prepareDataRequest);
                    txnHeader = new TxnHeader(prepareDataRequest.getClientId(), request.cxid, request.nonce,
                            -1, zks.getTime(), OpCode.prepareData);
                    txn = new PrepareDataTxn(prepareDataRequest.getClientId(), request.cxid, prepareDataRequest.getData());
                    break;
                case OpCode.sync:
                case OpCode.getData:
                case OpCode.boloskyGetData:
                case OpCode.ping:
                    break;
            }
        } catch (Exception e) {
            // log at error level as we are returning a marshalling
            // error to the user
            LOG.error("Failed to process " + request, e);

            StringBuilder sb = new StringBuilder();
            ByteBuffer bb = request.request;
            if (bb != null) {
                bb.rewind();
                while (bb.hasRemaining()) {
                    sb.append(Integer.toHexString(bb.get() & 0xff));
                }
            } else {
                sb.append("request buffer is null");
            }

            LOG.error("Dumping request buffer: 0x" + sb.toString());
            if (txnHeader != null) {
                txnHeader.setType(OpCode.error);
                txn = new ErrorTxn(Code.MARSHALLINGERROR.intValue());
            }
        }
        request.hdr = txnHeader;
        request.txn = txn;
        request.zxid = zks.getZxid();
        nextProcessor.processRequest(request);
    }

    public void processRequest(Request request) {
        // request.addRQRec(">prep="+zks.outstandingChanges.size());
        submittedRequests.add(request);
    }

    public void processRequest(Request[] request) {
        throw new RuntimeException("Not implemented");
    }

    public void shutdown() {
        submittedRequests.clear();
        submittedRequests.add(Request.requestOfDeath);
        nextProcessor.shutdown();
    }
}
